package cn.edu.zjicm.wordsnet_d.fragment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.WordDetailActivity;
import cn.edu.zjicm.wordsnet_d.data.DataManager;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.data.RelationShip;
import cn.edu.zjicm.wordsnet_d.data.Sentence;
import cn.edu.zjicm.wordsnet_d.data.StudyPlan;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.media.VoicePlayer;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.NightModeUtil;
import cn.edu.zjicm.wordsnet_d.util.TypefaceUtil;

public class CreatView {

	/* 创建搭配中的单词列表 */
	public static void reLoadWordListView(LinearLayout container, LayoutInflater mInflater, RelationShip relationShip, WordFactory wf, Context context) {
		container.removeAllViews();

		OneWord curWord = wf.getOneWordById(relationShip.getIndex_word_id());
		String[] rsEng = relationShip.getColloc_eng().split(" ");
		String[] relation = relationShip.getWord_str().split(";");
		final Map<Integer, Integer> map = new HashMap<Integer, Integer>();

		for (int i = 0; i < relation.length; i++) {
			String[] s = relation[i].split(",");
			if (s.length == 2)
				map.put(Integer.valueOf(s[1]), Integer.valueOf(s[0]));
		}
		container.addView(createWordView(mInflater, curWord, context));
		if (rsEng.length > 0) {
			for (int i = 0; i < rsEng.length; i++) {
				if (map.containsKey(i) && map.get(i) != curWord.getIndex_word_id()) {
					OneWord word = wf.getOneWordById(map.get(i));
					if (word == null)
						continue;
					View v = createWordView(mInflater, word, context);
					container.addView(v);
				}
			}
		}
		Sentence exa = relationShip.getExaSentence();
		if (exa != null) {
			View v = createExaSentenceView(exa, context);
			container.addView(v);
		}
	}

	/* 创建单词视图 */
	public static View createWordView(LayoutInflater mInflater, final OneWord word, final Context context) {
		View view = mInflater.inflate(R.layout.view_word_note_item1, null);

		TextView lemma = (TextView) view.findViewById(R.id.word_note_item_word);
		TextView phe = (TextView) view.findViewById(R.id.word_note_item_phe);
		TypefaceUtil.getInstance(context).setTypeface(phe);
		TextView traslation = (TextView) view.findViewById(R.id.word_note_item_translation);
		// LinearLayout readButton = (LinearLayout)
		// view.findViewById(R.id.read_button);
		LinearLayout readLayout = (LinearLayout) view.findViewById(R.id.word_note_item_layout);

		lemma.setText(word.getLemma());
		phe.setText(word.getPhonetic());
		traslation.setText(word.getSensesSenior());

		long start = System.currentTimeMillis();

		if (FileManager.isVoiceFileExist(context, word)) {
			readLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					VoicePlayer.getInstance(context).playWithNoCheckVoiceFile(word);
				}
			});
		} else {
			// readButton.setBackgroundDrawable(null);
			phe.setCompoundDrawables(null, null, null, null);
		}

		LogUtil.i("加载时间----" + (System.currentTimeMillis() - start));

		return view;
	}

	/* 创建单词的搭配列表 */
	public static void reLoadRelationShip(LinearLayout container, OneWord word, Context context) {
		if (container == null)
			return;
		container.removeAllViews();
		List<RelationShip> mRelationShipList = DataManager.getInstance().getRelationShipList(context, word.getIndex_word_id());
		if (mRelationShipList != null) {
			for (int i = 0; i < mRelationShipList.size(); i++) {
				RelationShip rs = mRelationShipList.get(i);
				View rsItem = createRelationshipItemView(rs, context);
				container.addView(rsItem);
			}
		}
	}

	/* 创建搭配视图 */
	private static View createRelationshipItemView(RelationShip rs, Context context) {
		View itemView = View.inflate(context, R.layout.view_relationship_item, null);

		// fill eng
		TextView enText = (TextView) itemView.findViewById(R.id.relation_en_string);
		createRelationEnContainerWithoutLink(enText, rs.getColloc_eng(), context);

		// fill cn
		TextView cnText = (TextView) itemView.findViewById(R.id.relation_cn_string);
		cnText.setText(rs.getColloc_cn());

		itemView.setPadding(0, 0, 0, 10);
		return itemView;
	}

	static void createRelationEnContainerWithoutLink(TextView tv, String str, Context context) {
		if (NightModeUtil.isNightModeNow())
			tv.setTextColor(context.getResources().getColor(R.color.word_color_night));// 学习界面(太简单，继续学习界面)的英文字颜色
		else
			tv.setTextColor(context.getResources().getColor(R.color.main_text_color2));// 学习界面(太简单，继续学习界面)的英文字颜色
		tv.setText(str);
		LinearLayout.LayoutParams para = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		para.rightMargin = (int) (10 * context.getResources().getDisplayMetrics().density);
		tv.setLayoutParams(para);
	}

	/* 创建例句视图 */
	private static View createExaSentenceView(Sentence se, Context context) {
		View itemView = View.inflate(context, R.layout.view_relationship_item, null);

		// fill eng
		TextView enText = (TextView) itemView.findViewById(R.id.relation_en_string);
		createRelationEnContainerWithoutLink(enText, se.getExa_eng(), context);

		// fill cn
		TextView cnText = (TextView) itemView.findViewById(R.id.relation_cn_string);
		cnText.setText(se.getExa_cn());

		itemView.setPadding(0, 100, 0, 10);
		return itemView;
	}

	private boolean mIsFirstLevel;// 标识是否第一层次的单词详情页，是的话可以跳转

	void createRelationEnContainerWithLink(LinearLayout relationEnContainer, RelationShip rs, final Context context, boolean mIsFirstLevel) {
		String[] rsEng = rs.getColloc_eng().split(" ");
		String[] relation = rs.getWord_str().split(";");
		final Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		for (int i = 0; i < relation.length; i += 1) {
			String[] s = relation[i].split(",");
			if (s.length == 2)
				map.put(Integer.valueOf(s[1]), Integer.valueOf(s[0]));
		}
		if (rsEng.length > 0) {
			for (int i = 0; i < rsEng.length; i++) {
				TextView tv = new TextView(context);
				tv.setGravity(Gravity.CENTER);
				tv.setTextSize(16);
				tv.setTextColor(context.getResources().getColor(R.color.word_text_color));
				tv.setText(rsEng[i]);
				if (map.containsKey(i) && mIsFirstLevel) {
					// is link
					final int linkId = map.get(i);
					tv.setBackgroundResource(R.drawable.write_underline_bg);
					// tv.setBackgroundResource(R.drawable.word_link_bg);
					tv.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							WordDetailActivity.startActivity(context, linkId);
						}
					});
				}
				// int padding = (int) (5 *
				// getActivity().getResources().getDisplayMetrics().density);
				// tv.setPadding(padding, 0, padding, 0);
				LinearLayout.LayoutParams para = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				para.rightMargin = (int) (10 * context.getResources().getDisplayMetrics().density);
				tv.setLayoutParams(para);
				relationEnContainer.addView(tv);
			}
		}
	}

	/**
	 * 
	 * @param affixLayout
	 * @param wordList
	 * @param testMode
	 * @param mContext
	 * @param affixTv
	 * @param lemmaType
	 *            1表示普通单词，2表示词组，3表示搭配
	 */
	public static void reloadAffix(LinearLayout affixLayout, List<OneWord> wordList, boolean testMode, Context mContext, View affixTv, int lemmaType) {
		if (affixLayout == null)
			return;
		affixLayout.removeAllViews();

		int level = 0;
		if (lemmaType == OneWord.LEMMA_TYPE_WORD && StudyPlan.isLearningWordBook(mContext)) {
			level = WordFactory.getInstance(mContext).getLevelByBookId(AppPreference.Book.BOOK_ID[AppPreference.getWordBookIndex(mContext)]);
		}

		for (int i = 0; i < wordList.size(); i++) {
			OneWord word = wordList.get(i);

			// 学习流程中，非正在学的单词书的形近词，忽略
			if (lemmaType == OneWord.LEMMA_TYPE_WORD && testMode && word.getLevel_min() > level)
				continue;

			View affixItemView = createAffixItemView(word, mContext);
			affixLayout.addView(affixItemView);
		}
		if (affixLayout.getChildCount() == 0) {
			affixTv.setVisibility(View.GONE);
		}
	}

	private static View createAffixItemView(OneWord word, Context mContext) {
		View affixItem = LayoutInflater.from(mContext).inflate(R.layout.view_affix_item, null);
		TextView affixEn = (TextView) affixItem.findViewById(R.id.affix_item_en);
		TextView affixCn = (TextView) affixItem.findViewById(R.id.affix_item_cn);
		TextView affixJi = (TextView) affixItem.findViewById(R.id.affix_item_ji);
		affixEn.setText(word.getLemma());
		affixCn.setText(word.getSensesSenior());
		if (word.getAff_content() != null && word.getAff_content().length() > 0) {
			affixJi.setVisibility(View.VISIBLE);
			affixJi.setText("[记]" + word.getAff_content());
		}
		affixItem.setPadding(0, 0, 0, 30);
		return affixItem;
	}

	public static void createChoiceWordView(LayoutInflater mInflater, Context context, LinearLayout container, OneWord[] oneWords, int rightIndex) {
		container.removeAllViews();
		for (int i = 0; i < oneWords.length; i++) {
			if (i == rightIndex)
				continue;
			container.addView(createWordView(mInflater, oneWords[i], context));
		}
	}
}
